package com.nc.cloud.admin.rest;

import com.nc.cloud.admin.biz.MenuBiz;
import com.nc.cloud.admin.biz.UserBiz;
import com.nc.cloud.admin.entity.Menu;
import com.nc.cloud.admin.entity.User;
import com.nc.cloud.authority.client.jwt.UserAuthUtil;
import com.nc.cloud.common.context.BaseContextHandler;
import com.nc.cloud.common.msg.ObjectRestResponse;
import com.nc.cloud.common.rest.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController extends BaseController<UserBiz, User> {

    @Autowired
    protected UserBiz userBiz;

    @Autowired
    protected MenuBiz menuBiz;

    @Autowired
    private UserAuthUtil userAuthUtil;

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> userInfo(String token) {
        Map<String, Object> result = new HashMap<>();
        try {
            String userId = userAuthUtil.getInfoFromToken(token).getId();
            User user = userBiz.selectById(userId);
            if (user != null) {
                user.setPwd(null);
            }
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("userCode", user.getCode());
            List<Menu> menus = menuBiz.findMenuOfUser(hashMap);

            result.put("userInfo", user);
            result.put("menus", menus);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @RequestMapping(value = "/local", method = RequestMethod.PUT)
    @ResponseBody
    public User updateLocale(@RequestBody User user) {
        String userId = BaseContextHandler.getUserID();
        if (userId != null) {
            User u = new User();
            u.setUid(userId);
            u.setLocal(user.getLocal());
            userBiz.updateSelectiveById(u);
            return u;
        }
        return null;
    }
}